<script>
    import Icon from './components/Icon.svelte';
    import Button from './components/Button.svelte';
    import Upload from './components/Upload.svelte';
    import Input from './components/Input.svelte';
    import Message from './components/Message.svelte';
    import Tooltip from './components/Tooltip.svelte';
    import axios from 'axios';
    import { getBase64, getPixel } from './utils';

    const bgUrl = './bg.jpeg',
          logoUrl = './favicon.png',
          actionUrl = 'ip/putImage',
          compareUrl = 'ip/compareImage',
          downloadUrl = 'ip/downloadImage',
          crxUrl = 'ip/pixelpiper.zip';
    let width = 0, height = 0, flag, compareName, errorMsg, successMsg, show, tooltip;
    let uploaders = [
        {
            id: 'design',
            title: '设计图',
            filename: '',
            url: ''
        },
        {
            id: 'code',
            title: '实现图',
            filename: '',
            url: ''
        }
    ];

    const handleCompare = () => {
        show = false;
        const len = uploaders.filter(f => !!f.filename).length;
        if(len == 2) {
            axios.post(compareUrl, {
                designName: uploaders[0]['filename'],
                codeName: uploaders[1]['filename'],
            }).then(res => {
                console.log('compare', res)
                if(res.data.success) { 
                    compareName = res.data.data.compareName;
                    return true
                } else {
                    flag = 'error';
                    show = true;
                    errorMsg = res.data.data
                } 
            }).then(c => {
                if(c) {
                    flag = 'success';
                    successMsg = '对比成功';
                    show = true;
                    handleDownload()
                    handleDelete()
                }
            })
        } else if(len == 1) {
            window.alert('设计图或开发图缺少，请确认已全部上传后再进行比较！')
        } else {
            window.alert('必须有图片才能进行比较！')
        }
    };

    const handleBeforeUpload = async function(rawFile, id) {
        const fileBase64 = await getBase64(rawFile);
        const res = await getPixel(fileBase64);
        // console.log('res', res)
        if(res.width == width && res.height == height) {
            switch (id) {
                case 'design':
                    uploaders[0]['url'] = fileBase64
                    break;
                case 'code':
                    uploaders[1]['url'] = fileBase64
                    break;
                default:
                    break;
            }
            return true;
        } else {
            window.alert('上传图片不符合分比率要求');
            return false;
        }
    }

    const handleSuccess = (response, rawFile, id) => {
        console.log('response', response, rawFile, id);
        if(response.success) {
            switch (id) {
                case 'design':
                    uploaders[0]['filename'] = response.data.filename
                    break;
                case 'code':
                    uploaders[1]['filename'] = response.data.filename
                    break;
                default:
                    break;
            }
        }
    }

    function handleDownload() {
        axios({
            method: 'POST',
            url: downloadUrl,
            responseType: 'blob',
            data: {
                compareName: compareName
            }
        }).then(res => {
            console.log('download', res)
            if(res.status == 200) {
                var blob = new Blob([res.data]);
                // 创建一个URL对象
                var url = window.URL.createObjectURL(blob);
                console.log('url', url)
                // 创建一个a标签
                var a = document.createElement("a");
                a.href = url;
                a.download = compareName;// 这里指定下载文件的文件名
                a.click();
                // 释放之前创建的URL对象
                window.URL.revokeObjectURL(url);
            }
        })
    }

    function handleDelete() {
        uploaders = [
        {
            id: 'design',
            title: '设计图',
            filename: '',
            url: ''
        },
        {
            id: 'code',
            title: '实现图',
            filename: '',
            url: ''
        }
    ];
    }
</script>

<style>
    .pixel-piper {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .main {
        width: 600px;
        margin: 0 auto;
        padding: 20px;
        border: 1px solid #eee;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 0 10px #e0e0e0;
    }

    .main .logo-container {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .logo-container .logo:hover {
        opacity: 90%;
        cursor: pointer;
    }

    .main .select-container {
        display: flex;
        align-items: center;
        align-content: center;
        justify-content: center;
        justify-items: center;
        line-height: 40px;
    }

    .main .upload-container {
        display: flex;
        padding: 0 0 10px 0;
        justify-content: space-between;
        text-align: center;
    }

    .main .button-container {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .main .info-container {
        text-align: center;
        color: red;
        font-size: 12px;
        margin: 10px 0;
    }
</style>

<div class="pixel-piper" style="{`background: url(${bgUrl}) no-repeat; background-size: cover`}">
    <section class="main">
        <div class="logo-container">
            <Tooltip content="点击logo可下载chrome插件" {tooltip}>
                <a href={crxUrl}>
                    <img 
                        class="logo" 
                        src={logoUrl} 
                        alt="logo" 
                        width="100px" 
                        on:mouseenter={() => tooltip=true} 
                        on:mouseleave={() => tooltip=false}
                    >
                </a>
            </Tooltip>
        </div>
        <div class="select-container">
            <p class="select-name"><Input bind:value={width} /> x <Input bind:value={height} /> </p> 
        </div>
        <div class="upload-container">
            {#each uploaders as uploader}
            <div class="uploader">
                <Upload
                    id={uploader.id}
                    onSuccess={handleSuccess} 
                    beforeUpload={handleBeforeUpload} 
                    action={actionUrl}
                >
                    {#if !uploader.url}
                        <Icon name="iconplus" />
                    {:else}
                        <img class="uploader-image" style="object-fit: contain;" width="250" height="250" src={uploader.url} alt={uploader.id} />
                    {/if}
                </Upload>
                <span class="uploader-title">{uploader.title}</span>
            </div>
            {/each}
        </div>
        <div class="info-container">
            {#if uploaders.filter(f => !!f.filename).length == 2}
                <span class="info-tips">注：请在两分钟内进行图片对比！！</span>
            {/if}
        </div>
        <div class="button-container">
            <Button icon="iconposition" on:click={handleCompare} type="primary">对比</Button>
            {#if uploaders.filter(f => !!f.filename).length == 2}
                <div style="margin-left: 10px">
                    <Button  icon="icondelete" on:click={handleDelete} type="default">清除图片</Button>
                </div>
            {/if}
        </div>
    </section>
    {#if flag == 'success'}
        <Message type="success" {show} >{successMsg}</Message>
    {:else if flag == 'error'}
        <Message type="error" {show} >{errorMsg}</Message>
    {/if}
</div>




